/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import java.util.List;
import java.util.Set;
import models.Category;
import models.Course;
import models.User;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Aster
 */
public class CourseDao {
    private final Session session;
    
    public CourseDao(Session session) {
        this.session = session;
    }
    
      public List<Course> findAll() {
        Transaction tx = session.beginTransaction();
        List<Course> list = session.createQuery("from Course").list();
        tx.commit();
        return list;
    }
    
    public void save(Course course) {
        Transaction tx = session.beginTransaction();
        session.save(course);
        tx.commit();
    }

    public void update(Course course) {
        Transaction tx = session.beginTransaction();
        session.update(course);
        tx.commit();
    }

    public Course get(long id) {
        return (Course) session.get(Course.class, id);
    }
    
    public void delete(Course course) {
        Transaction tx = session.beginTransaction();
        
        List<Category> list = session.createQuery("from Category").list();
        for (Category c: list) {
            c.getCourses().remove(course);
        }
        
        List<User> listUser = session.createQuery("from User").list();
        for(User user : listUser){
            user.getCourses().remove(course);
            user.getStudentCourses().remove(course);
        }
        
        session.delete(course);
        tx.commit();
        System.out.println("delete gelukt?");
    }
}
